<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style>
			* {
				margin: 0;
				padding: 0;
			}

			div {
				width: 100px;
				height: 100px;
				background-color: aqua;
				position: absolute;
				top: 100px;
				left: 300px;
			}
		</style>
	</head>
	<body>
		<div>
		</div>
	</body>
	<script type="text/javascript">
		var div = document.querySelector("div")

		// 鼠标按下
		div.onmousedown = function(e) {
			e = e || window.event;
			var x = e.offsetX;
			var y = e.offsetY;
			// 鼠标移动
			document.onmousemove = function(e) {
				e = e || window.event;
				var left = e.pageX - x;
				var top = e.pageY - y;
				if (left < 0) {
					left = 0;
				}
				if (left > window.innerWidth - div.offsetWidth) {
					left = window.innerWidth - div.offsetWidth;
				}
				if (top < 0) {
					top = 0;
				}
				if (top > window.innerHeight - div.offsetHeight) {
					top = window.innerHeight - div.offsetHeight;
				}

				div.style.left = left + "px";
				div.style.top = top + "px";
			}
			// 鼠标松开
			document.onmouseup = function() {
				document.onmousemove = null;
			}
		}
	</script>
</html>
